package org.ratingviewer.resources;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;

import javax.swing.*;

public class Resources {

	private static final String SUFFIX_ITEM_KEY = ".key";
	private static final String SUFFIX_ITEM_DESC = ".desc";
	private static final String SUFFIX_ITEM_MNEMONIC = ".mnemonic";
	private static final String SUFFIX_ITEM_LABEL = ".label";

	public static final String IMAGE_MAINICON = "/org/ratingviewer/resources/images/MainIcon.gif";

	private static volatile Resources instance;

	private final ResourceBundle bundle;

	private Resources() {
		super();

		bundle = ResourceBundle.getBundle("org.ratingviewer.resources.RatingViewer");
	}

	public static synchronized Resources getInstance() {
		if (instance == null)
			instance = new Resources();
		return instance;
	}

	public ResourceBundle getResourceBundle() {
		return bundle;
	}

	public String getString(String key) {
		String value = "";
		try {
			value = bundle.getString(key);
		} catch (MissingResourceException ex) {
			System.err.println(MessageFormat.format("Couldn''t find resource: {0}.", ex.getLocalizedMessage()));
			value = "??" + key + "??";
		}
		return value;
	}

	public char getChar(String key) {
		String value = "?";
		try {
			value = bundle.getString(key);
		} catch (MissingResourceException ex) {
			System.err.println(MessageFormat.format("Couldn''t find resource: {0}.", ex.getLocalizedMessage()));
		}
		return value.charAt(0);
	}

	public Image getImage(String key) {
		URL resourceURL = Resources.class.getResource(key);
		return Toolkit.getDefaultToolkit().createImage(resourceURL);
	}

	public void fillActionFrom(String item, Action action) {
		if (action == null || item == null)
			return;

		if (!bundle.containsKey(label(item)))
			throw new IllegalArgumentException(MessageFormat.format("Action item ''{0}'' must define label "
					+ "element in resources.", item));
		
		action.putValue(Action.NAME, getString(label(item)));
		if (bundle.containsKey(mnemonic(item)))
			action.putValue(Action.MNEMONIC_KEY, (int) getChar(mnemonic(item)));

		if (bundle.containsKey(key(item)))
			action.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(getString(key(item))));

		if (bundle.containsKey(desc(item)))
			action.putValue(Action.SHORT_DESCRIPTION, getString(desc(item)));
	}

	private String label(String item) {
		return item + SUFFIX_ITEM_LABEL;
	}

	private String mnemonic(String item) {
		return item + SUFFIX_ITEM_MNEMONIC;
	}

	private String desc(String item) {
		return item + SUFFIX_ITEM_DESC;
	}

	private String key(String item) {
		return item + SUFFIX_ITEM_KEY;
	}
}
